<?php


function FormatMoney($money){
    if($money >= 10000){
        return sprintf("%.2f", $money/10000);
    }else{
        return $money;
    }
}

/**
 *  * isUsername函数:检测是否符合用户名格式
 *  * $Argv是要检测的用户名参数
 *  * $RegExp是要进行检测的正则语句
 *  * 返回值:符合用户名格式返回用户名,不是返回false
 *  */
function isUsername($Argv) {
    $RegExp = '/^[a-zA-Z0-9_]{3,16}$/'; //由大小写字母跟数字组成并且长度在3-16字符直接
    return preg_match($RegExp, $Argv) ? $Argv : false;
}

function isLoginUsername($Argv) {
    $RegExp = '/^[a-zA-Z\x{4e00}-\x{9fa5}]{2,20}$/u';
    return preg_match($RegExp, $Argv) ? $Argv : false;
}

/**
 * isMail函数:检测是否为正确的邮件格式
 * 返回值:是正确的邮件格式返回邮件,不是返回false
 */
function isMail($Argv) {
    $RegExp = '/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/';
    return preg_match($RegExp, $Argv) ? $Argv : false;
}

/**
 * isSmae函数:检测参数的值是否相同
 * 返回值:相同返回true,不相同返回false
 */
function isSame($ArgvOne, $ArgvTwo, $Force = false) {
    return $Force ? $ArgvOne === $ArgvTwo : $ArgvOne == $ArgvTwo;
}

/**
 * isQQ函数:检测参数的值是否符合QQ号码的格式
 * 返回值:是正确的QQ号码返回QQ号码,不是返回false
 */
function isQQ($Argv) {
    $RegExp = '/^[1-9][0-9]{5,11}$/';
    return preg_match($RegExp, $Argv) ? $Argv : false;
}

/**
 * 44. * isMobile函数:检测参数的值是否为正确的中国手机号码格式
 * 45. * 返回值:是正确的手机号码返回手机号码,不是返回false
 * 46. */
//function isMobile($Argv) {
//    $RegExp = '/^(?:13|15|18)[0-9]{9}$/';
//    return preg_match($RegExp, $Argv) ? $Argv : false;
//}


function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

/**
 * 62. * isNickname函数:检测参数的值是否为正确的昵称格式(Beta)
 * 63. * 返回值:是正确的昵称格式返回昵称格式,不是返回false
 * 64. */
function isNickname($Argv) {
    $RegExp = '/^\s*$|^c:\\con\\con$|[%,\*\"\s\t\<\>\&\'\(\)]|\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8/is'; //Copy From DZ
    return preg_match($RegExp, $Argv) ? $Argv : false;
}

/**
 * isChinese函数:检测参数是否为中文
 * 返回值:是返回参数,不是返回false
 */
function isChinese($Argv, $Encoding = 'utf8') {
    $RegExp = $Encoding == 'utf8' ? '/^[\x{4e00}-\x{9fa5}]+$/u' : '/^([\x80-\xFF][\x80-\xFF])+$/';
    return preg_match($RegExp, $Argv) ? $Argv : False;
}

function isIp($Argv) {
    $RegExp = '/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/';
    return preg_match($RegExp, $Argv) ? $Argv : False;
}

/**
 * 检测是否是第三方支付平台账号（邮箱或手机）
 */
function isPayacc($Argv) {
    $pattern = '/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i';
    if (strpos($Argv, '@') || preg_match($pattern, $Argv)) {
        return true;
    }
    return false;
}

/**
 * 对邮箱或手机进行标星
 */
function hideStar($str) {
    if (strpos($str, '@')) {
        $email_array = explode("@", $str);
        $prevfix     = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3);
        $count       = 0;
        $str         = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $str, -1, $count);
        $rs          = $prevfix . $str;
    } else {
        $pattern = '/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i';
        if (preg_match($pattern, $str)) {
            $rs = preg_replace($pattern, '$1****$2', $str);
        } else {
            $rs = substr($str, 0, 3) . "***" . substr($str, -3);
        }
    }
    return $rs;
}

function build_order_no($prefix = 'O') {
    return $prefix . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 生成商品货号
 * @return string
 */
function createGoodsNo() {
    return 'SD' . time() . rand(10000, 99999);
}

function multi_unique($array) {
    foreach ($array as $k => $v) {
        $new = [];
        foreach ($v as $key => $val) {
            $new[$key] = serialize($val);
        }
        $uniq[$k] = array_unique($new);
    }

    foreach ($uniq as $key => $val) {
        $newArr = [];
        foreach ($val as $j => $c) {
            $newArr[$j] = unserialize($c);
        }

        $newArray[$key] = $newArr;
    }
    return $newArray;
}

if (!function_exists('settings')) {

    function settings($key = null) {
        if (is_null($key)) {
            return app('settingRepository');
        }
        return app('settingRepository')->getSetting($key);
    }
}

/**
 * 格式化字符串
 * @param $text
 * @param null $length
 * @return string
 */
function plainText($text, $length = null) {
    $text = strip_tags($text);

    $length = (int)$length;
    if (($length > 0) && (mb_strlen($text) > $length)) {
        $text = mb_substr($text, 0, $length, 'UTF-8');
        $text .= '...';
    }
    return $text;
}

/**
 * 格式化标准日期形式 1986-5-1 to 1986-05-01
 * @param $date
 */
function plainDate($date) {
    $dateArr = explode('-', $date);
    foreach ($dateArr as $key => $val) {
        if (strlen($val) < 2) {
            $dateArr[$key] = '0' . $val;
        }
    }
    return implode('-', $dateArr);
}

/**
 * 生成会员卡号
 * @return string
 */
function createCardNo() {
    return '10' . time() . rand(10, 999);
}


/**
 * 生成随机字符串
 * @param int $length
 * @return string
 */
function generate_random_string($length = 10) {
    $characters       = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString     = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}


/**
 * 递归创建目录
 *
 * 与 mkdir 不同之处在于支持一次性多级创建, 比如 /dir/sub/dir/
 *
 * @param  string
 * @param  int
 * @return boolean
 */
function make_dir($dir, $permission = 0777) {
    $dir = rtrim($dir, '/') . '/';

    if (is_dir($dir)) {
        return TRUE;
    }

    if (!make_dir(dirname($dir), $permission)) {
        return FALSE;
    }

    return @mkdir($dir, $permission);
}

function create_content_image_from_base64($type, $id, $base64_string, $prefix = null) {
    $out_file_path = '/uploads/' . $type . '/' . $id . '/';

    $real_file_path = public_path() . $out_file_path;

    if (!file_exists($real_file_path)) {
        make_dir($real_file_path);
    }

    $file_name = generate_random_string();

    if ($prefix) {
        $file_name = $prefix . '-' . $file_name;
    }

    base64_to_image($base64_string, $real_file_path . $file_name . '.jpg');

    return $out_file_path . $file_name . '.jpg';
}

/**
 * 把64位的图片编码数据转化为实际的图片存储
 * @param $base64_sting
 * @param $output_file
 * @return mixed
 */
function base64_to_image($base64_sting, $output_file) {
    $base64_body = substr(strstr($base64_sting, ','), 1);
    $data        = base64_decode($base64_body);
    file_put_contents($output_file, $data);
    return $output_file;
}

function my_image_resize($src_file, $dst_file, $new_width, $new_height) {
    $new_width  = intval($new_width);
    $new_height = intval($new_width);
    if ($new_width < 1 || $new_height < 1) {
        echo "params width or height error !";
        exit();
    }
    if (!file_exists($src_file)) {
        echo $src_file . " is not exists !";
        exit();
    }
    // 图像类型
    $type         = exif_imagetype($src_file);
    $support_type = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
    if (!in_array($type, $support_type, true)) {
        echo "this type of image does not support! only support jpg , gif or png";
        exit();
    }
    //Load image
    switch ($type) {
        case IMAGETYPE_JPEG :
            $src_img = imagecreatefromjpeg($src_file);
            break;
        case IMAGETYPE_PNG :
            $src_img = imagecreatefrompng($src_file);
            break;
        case IMAGETYPE_GIF :
            $src_img = imagecreatefromgif($src_file);
            break;
        default:
            echo "Load image error!";
            exit();
    }
    $w       = imagesx($src_img);
    $h       = imagesy($src_img);
    $ratio_w = 1.0 * $new_width / $w;
    $ratio_h = 1.0 * $new_height / $h;
    $ratio   = 1.0;
    // 生成的图像的高宽比原来的都小，或都大 ，原则是 取大比例放大，取大比例缩小（缩小的比例就比较小了）
    if (($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
        if ($ratio_w < $ratio_h) {
            $ratio = $ratio_h; // 情况一，宽度的比例比高度方向的小，按照高度的比例标准来裁剪或放大
        } else {
            $ratio = $ratio_w;
        }
        // 定义一个中间的临时图像，该图像的宽高比 正好满足目标要求
        $inter_w   = (int)($new_width / $ratio);
        $inter_h   = (int)($new_height / $ratio);
        $inter_img = imagecreatetruecolor($inter_w, $inter_h);
        //var_dump($inter_img);
        imagecopy($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h);
        // 生成一个以最大边长度为大小的是目标图像$ratio比例的临时图像
        // 定义一个新的图像
        $new_img = imagecreatetruecolor($new_width, $new_height);
        //var_dump($new_img);exit();
        imagecopyresampled($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height, $inter_w, $inter_h);
        switch ($type) {
            case IMAGETYPE_JPEG :
                imagejpeg($new_img, $dst_file, 100); // 存储图像
                break;
            case IMAGETYPE_PNG :
                imagepng($new_img, $dst_file, 100);
                break;
            case IMAGETYPE_GIF :
                imagegif($new_img, $dst_file, 100);
                break;
            default:
                break;
        }
    } // end if 1
    // 2 目标图像 的一个边大于原图，一个边小于原图 ，先放大平普图像，然后裁剪
    // =if( ($ratio_w < 1 && $ratio_h > 1) || ($ratio_w >1 && $ratio_h <1) )
    else {
        $ratio = $ratio_h > $ratio_w ? $ratio_h : $ratio_w; //取比例大的那个值
        // 定义一个中间的大图像，该图像的高或宽和目标图像相等，然后对原图放大
        $inter_w   = (int)($w * $ratio);
        $inter_h   = (int)($h * $ratio);
        $inter_img = imagecreatetruecolor($inter_w, $inter_h);
        //将原图缩放比例后裁剪
        imagecopyresampled($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h, $w, $h);
        // 定义一个新的图像
        $new_img = imagecreatetruecolor($new_width, $new_height);
        imagecopy($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height);
        switch ($type) {
            case IMAGETYPE_JPEG :
                imagejpeg($new_img, $dst_file, 100); // 存储图像
                break;
            case IMAGETYPE_PNG :
                imagepng($new_img, $dst_file, 100);
                break;
            case IMAGETYPE_GIF :
                imagegif($new_img, $dst_file, 100);
                break;
            default:
                break;
        }
    }// if3
}// end function





/**
 * @param $workerStar
 * @return float|int
 * 不同星级不同的百分比
 */
function rate_choose($workerStar){
    switch ($workerStar) {
        case 1:
            $workerStar = 1;
            break;
        case 2:
            $workerStar = 1.1;
            break;
        case 3:
            $workerStar = 1.2;
            break;
        case 4:
            $workerStar = 1.3;
            break;
        case 5:
            $workerStar = 1.4;
            break;
        default:
            $workerStar = 1;
    }
    return $workerStar;
}

/**
 * @param $workerStar
 * @return float|int
 * 1 待审核 2 二审通过 3 三审通过 4 审核不通过 5 已打款
 * 审核状态
 */
function cash_out_status($status){

    switch ($status) {
        case 1:
            $status_info = '待审核';
            break;
        case 2:
            $status_info = '二审通过';
            break;
        case 3:
            $status_info = '三审通过';
            break;
        case 4:
            $status_info = '审核不通过';
            break;
        case 5:
            $status_info = '已打款';
            break;
        default:
            $status_info = '待审核';
    }
    return $status_info;
}

/**
 * @param $workerStar
 * @return float|int
 * work状态
 */
function work_status($status) {
    switch ($status) {
        case 0:
            $status_work = '业主未确认工作者';
            break;
        case 1:
            $status_work = '已确认工作者';
            break;
        case 2:
            $status_work = '任务进行中';
            break;
        case 3:
            $status_work = '成功结束';
            break;
        case 4:
            $status_work = '失败结束';
            break;
        default:
            $status_work = 1;
    }
    return $status_work;
}


/**
 * @param $workerStar
 * @return float|int
 * work_offer状态
 */
function work_offer_status($status) {
    switch ($status) {
        case 0:
            $work_offer_status = '未开始';
            break;
        case 1:
            $work_offer_status = '工作者提交';
            break;
        case 2:
            $work_offer_status = '业主确认';
            break;
        case 3:
            $work_offer_status = '业主退回';
            break;
        case 3.5:
            $work_offer_status = '监理退回';
            break;
        case 4:
            $work_offer_status = '完成';
            break;
        default:
            $work_offer_status = '工作者提交';
    }
    return $work_offer_status;
}


/**
 * @param $img_type
 * @return string
 * 图片类型
 */
function img_type($img_type) {
    switch ($img_type) {
        case 1:
            $img_type_name = '初步设计';
            break;
        case 2:
            $img_type_name = '深化设计';
            break;
        default:
            $img_type_name = '初步设计';
    }
    return $img_type_name;
}

/**
 * @param $img_type
 * @return string
 * 工程类型
 */
function get_project_type($project_type) {
    switch ($project_type) {
        case 1:
            $project_type_name = '拆除工程';
            break;
        case 2:
            $project_type_name = '水电工程';
            break;
        case 3:
            $project_type_name = '防水工程';
            break;
        case 4:
            $project_type_name = '泥工工程';
            break;
        case 5:
            $project_type_name = '木工工程';
            break;
        case 6:
            $project_type_name = '油漆工程';
            break;
        case 7:
            $project_type_name = '其他工程';
            break;
        default:
            $project_type_name = '其他工程';
    }
    return $project_type_name;
}

function work_offer_status_title($status){
    //进程 0未开始 1工作端submit 1.5监理确认 2用户commit 3业主退回 3.5监理退回 4done
    switch ($status){
        case 0:
            $status_title = '未开始';
            break;
        case 1:
            $status_title = '提交';
            break;
        case 1.5:
            $status_title = '监理确认';
            break;
        case 2:
            $status_title = '用户确认';
            break;
        case 3:
            $status_title = '业主退回';
            break;
        case 3.5:
            $status_title = '监理退回';
            break;
        case 4:
            $status_title = '完成';
            break;
        default:
            $status_title = '未开始';
    }
    return $status_title;
}




/**
 * @param $project_type
 * @return int
 * 根据project_type获取上级pid
 */
function get_pid_from_project_type($project_type){
    switch ($project_type) {
        case 1:
            $pid = 27;
            break;
        case 2:
            $pid = 57;
            break;
        case 3:
            $pid = 105;
            break;
        case 4:
            $pid = 108;
            break;
        case 5:
            $pid = 157;
            break;
        case 6:
            $pid = 300;
            break;
        case 7:
            $pid = 1;
            break;
        default:
            $pid = 27;
    }
    return $pid;
}

/**
 * @param $img_type
 * @return string
 */
function img_name($img_name_eng) {
    switch ($img_name_eng) {
        case 'plane_img':
            $img_name_china = '平面图';
            break;
        case 'effect_img':
            $img_name_china = '参考效果图';
            break;
        case 'hydroelectric_img':
            $img_name_china = '参考效果图';
            break;
        case 'construct_img':
            $img_name_china = '参考效果图';
            break;
        case 'deep_1':
            $img_name_china = '平面布局图';
            break;
        case 'deep_2':
            $img_name_china = '原始结构';
            break;
        case 'deep_3':
            $img_name_china = '结构拆改';
            break;
        case 'deep_4':
            $img_name_china = '墙体地位';
            break;
        case 'deep_5':
            $img_name_china = '平面索引';
            break;
        case 'deep_6':
            $img_name_china = '天花布局';
            break;
        case 'deep_7':
            $img_name_china = '墙地面铺贴图';
            break;
        case 'deep_8':
            $img_name_china = '水电布局图';
            break;
        case 'deep_9':
            $img_name_china = '效果图';
            break;
        case 'deep_10':
            $img_name_china = '材料说明';
            break;
        default:
            $img_name_china = '图纸';
    }
    return $img_name_china;
}

/**
 * @param $user_type_id
 * @return string
 * 设计师
 */
function get_user_type_name($user_type_id){
    switch ($user_type_id) {
        case 1:
            $user_type_name = '业主';
            break;
        case 2:
            $user_type_name = '设计师';
            break;
        case 3:
            $user_type_name = '管家';
            break;
        case 4:
            $user_type_name = '监理';
            break;
        case 5:
            $user_type_name = '工人';
            break;
        default:
            $user_type_name = '工人';
    }
    return $user_type_name;
}



function get_work_type_name($work_type){
    switch ($work_type) {
        case 1:
            $work_type_name = '管家';
            break;
        case 2:
            $work_type_name = '监理';
            break;
        case 5:
            $work_type_name = '泥水工';
            break;
        case 6:
            $work_type_name = '木工';
            break;
        case 7:
            $work_type_name = '水电工';
            break;
        case 8:
            $work_type_name = '油漆工';
            break;
        case 9:
            $work_type_name = '安装工';
            break;
        case 10:
            $work_type_name = '拆除工';
            break;
        default:
            $work_type_name = '工作者';
    }
    return $work_type_name;
}


function get_work_type_name_other($work_type){
    switch ($work_type) {
        case 1:
            $work_type_name = '管家';
            break;
        case 2:
            $work_type_name = '监理';
            break;
        case 5:
            $work_type_name = '泥水';
            break;
        case 6:
            $work_type_name = '木工';
            break;
        case 7:
            $work_type_name = '水电';
            break;
        case 8:
            $work_type_name = '油漆';
            break;
        case 9:
            $work_type_name = '安装';
            break;
        case 10:
            $work_type_name = '拆除';
            break;
        default:
            $work_type_name = '工作者';
    }
    return $work_type_name;
}


/**
 * 加密方法
 * @param string $str
 * @return string
 */
function encrypt($str,$screct_key){
    //AES, 128 模式加密数据 CBC
    $screct_key = base64_decode($screct_key);
    $str = trim($str);
    $str = addPKCS7Padding($str);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
    $encrypt_str =  mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
    return base64_encode($encrypt_str);
}

/**
 * 解密方法
 * @param string $str
 * @return string
 */
function decrypt($str,$screct_key){
    //AES, 128 模式加密数据 CBC
    $str = base64_decode($str);
    $screct_key = base64_decode($screct_key);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
    $encrypt_str =  mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
    $encrypt_str = trim($encrypt_str);

    $encrypt_str = stripPKSC7Padding($encrypt_str);
    return $encrypt_str;

}

/**
 * 填充算法
 * @param string $source
 * @return string
 */
function addPKCS7Padding($source){
    $source = trim($source);
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

    $pad = $block - (strlen($source) % $block);
    if ($pad <= $block) {
        $char = chr($pad);
        $source .= str_repeat($char, $pad);
    }
    return $source;
}
/**
 * 移去填充算法
 * @param string $source
 * @return string
 */
function stripPKSC7Padding($source){
    $source = trim($source);
    $char = substr($source, -1);
    $num = ord($char);
    if($num==62)return $source;
    $source = substr($source,0,-$num);
    return $source;
}

/**
 * @param $img
 * @return string
 * 图片类型
 */
function start_img_type($img) {
    switch ($img) {
        case 'ad_img':
            $img_name = '广告图片';
            break;
        case 'help_img':
            $img_name = '引导图片';
            break;
        default:
            $img_name = '广告图片';
    }
    return $img_name;
}

/**
 * @param $string
 * @return mixed|string
 *URL安全的字符串编码
 */
function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

function getGradeName($integral){
    if ($integral < 100) {
        $gradename = '实习菜鸟';
    } elseif ($integral >= 100 && $integral <= 300) {
        $gradename = '实习菜鸟';
    } elseif ($integral > 300 && $integral <= 500) {
        $gradename = '马路杀手';
    } elseif ($integral > 500 && $integral <= 1000) {
        $gradename = '旋风车手';
    } elseif ($integral > 1000 && $integral <= 3000) {
        $gradename = '炫酷车侠';

    } elseif ($integral > 3000 && $integral <= 4000) {
        $gradename = '极品车王';
    } else {
        $gradename = '车神第一等';
    }
    return $gradename;
}

/**
 * @param $integral
 * @return string
 * 获取积分等级
 */
function getGradeLevel($integral){
    if ($integral < 100) {
        $grade_level = 1;
    } elseif ($integral >= 100 && $integral <= 300) {
        $grade_level = 1;
    } elseif ($integral > 300 && $integral <= 500) {
        $grade_level = 2;
    } elseif ($integral > 500 && $integral <= 1000) {
        $grade_level = 3;
    } elseif ($integral > 1000 && $integral <= 3000) {
        $grade_level = 4;

    } elseif ($integral > 3000 && $integral <= 4000) {
        $grade_level = 5;
    } else {
        $grade_level = 5;
    }
    return $grade_level;
}


/**
 * @param $type
 * @return mixed|string
 * 1资讯,2视频,3测评,4活动,5快讯,6音频
 */
function getGradeByLevel($type) {
    $list = [
        1 => 100,
        2 => 300,
        3 => 500,
        4 => 1000,
        5 => 3000
    ];

    return isset($list[$type]) ? $list[$type] : 100;
}


/**
 * @param $type
 * @return mixed|string
 * 1资讯,2视频,3测评,4活动,5快讯,6音频
 */
function programa_name($type) {
    $list = [
        1 => "资讯",
        2 => "视频",
        3 => "测评",
        4 => "活动",
        5 => "快讯",
        6 => "音频"
    ];

    return isset($list[$type]) ? $list[$type] : "数据错误";
}

/**
 * @param int $len
 * @param string $format
 * @return string
 * 随机字符串
 */
function randStr($len = 5, $format = 'NUMBER')
{
    switch ($format) {
        case 'ALL':
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
            break;
        case 'CHAR':
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~';
            break;
        case 'NUMBER':
            $chars = '0123456789';
            break;
        default :
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
            break;
    }
    mt_srand((double)microtime() * 40400 * getmypid());
    $password = "";
    while (strlen($password) < $len) {
        $password .= substr($chars, (mt_rand() % strlen($chars)), 1);
    }
    return $password;
}


function get_audio_tag($tag){
    $list = [
        1 => "热点聚焦",
    ];

    return isset($list[$tag]) ? $list[$tag] : "无";
}

/**
 * @param $tag
 * @return mixed|string
 *
 */
function get_platform_name($tag){
    $list = [
        1 => "APP",
        2 => "微信小程序",
        3 => "微信公众号",
        4 => "PC",
    ];
    return isset($list[$tag]) ? $list[$tag] : "无";
}


/**
 *求两个已知经纬度之间的距离,单位为米
 *@param lng1,lng2 经度
 *@param lat1,lat2 纬度
 *@return float 距离，单位米
 *@author www.phpernote.com
 **/
function getdistance($lng1, $lat1, $lng2, $lat2)
{
    //将角度转为狐度
    $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a       = $radLat1 - $radLat2;
    $b       = $radLng1 - $radLng2;
    $s       = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2),
                2))) * 6378.137 * 1000;
    return $s;
}


/**
 * 更新密码
 *
 * @param string $newPlainPassword
 */
function encryPassword($newPlainPassword)
{

    //$password = 'aspirantzhang';
    //var_dump(password_hash($password, PASSWORD_DEFAULT),['cost' => 11]);
    //输出：string(60) "$2y$10$lgbL3K4uh1rbIxu4KrYjteZBLHUfL.wQDp/R1FrAGt.FVCvAB5NAu"

    $password = password_hash($newPlainPassword, PASSWORD_BCRYPT, ['cost' => 11]);
    return $password;
}

/**
 * 验证密码是否正确
 *
 * @param string $plainPassword 用户密码的明文
 * @param bool  $autoRehash    是否自动重新计算下密码的hash值（如果有必要的话）
 * @return boo
 */
function verifyPassword($plainPassword,$password_hash)
{

    //    $password_hash = '$2y$10$lgbL3K4uh1rbIxu4KrYjteZBLHUfL.wQDp/R1FrAGt.FVCvAB5NAu';
    //    var_dump(password_verify('aspirantzhang', $password_hash));

    return password_verify($plainPassword, $password_hash);
}




/**
 * 检测字符串为json数据
 *
 * @param $str
 * @return bool
 */
function isJson($str)
{
    json_decode($str);
    return (json_last_error() == JSON_ERROR_NONE);
}


/**
 * @return string
 * 浏览器类型
 */
function getBrowser()
{
    $agent = $_SERVER["HTTP_USER_AGENT"];
    if (strpos($agent, 'MSIE') !== false || strpos($agent, 'rv:11.0')) //ie11判断
    {
        return "ie";
    } else {
        if (strpos($agent, 'Firefox') !== false) {
            return "firefox";
        } else {
            if (strpos($agent, 'Chrome') !== false) {
                return "chrome";
            } else {
                if (strpos($agent, 'Opera') !== false) {
                    return 'opera';
                } else {
                    if ((strpos($agent, 'Chrome') == false) && strpos($agent, 'Safari') !== false) {
                        return 'safari';
                    } else {
                        return 'unknown';
                    }
                }
            }
        }
    }
}


/**
 * @param $data
 * 把null消除
 */
function changeNull($data)
{
    foreach ($data as $item => $value) {
        foreach ($value as $n => $m) {
            if ($m === null) {
                $data[$item][$n] = '';
            }
        }
    }
    return $data;
}

/**
 * @param $data
 * 把null消除
 */

function changeNullFirst($data)
{

    foreach ($data as $item => $value) {
        if ($data[$item] === null) {
            $data[$item] = '';
        }
    }

    return $data;
}


/**
 * 反序列化label
 */
function unserializeLabel($data)
{
    $arr_label = [];
    if (!empty($data)) {
        foreach (unserialize($data) as $item => $value) {
            $arr_label[$item]['name'] = \app\common\model\Label::where('id', $value)->value('name');
            $arr_label[$item]['id'] = \app\common\model\Label::where('id', $value)->value('id');
        }
    }
    return $arr_label;
}


/**
 * 获取id集合
 */
function getIdCollect($data){
    $all_ids = [];
    foreach ($data as $k=>$value){
        $all_ids[] = $value['id'];
    }
    return array_unique($all_ids);
}


function multi_array_sort($arr,$key,$type=SORT_REGULAR,$short=SORT_DESC){
    foreach ($arr as $k => $v){
        $name[$k] = $v[$key];
    }
    array_multisort($name,$type,$short,$arr);
    return $arr;
}



// 获取key值，进行排序，然后整理成二维数组
function array_sort($arr,$key,$type='asc'){
    $keysvalue = $new_array = array();
    // 获取key
    foreach ($arr as $k=>$v){
        $keysvalue[$k] = $v[$key];
    }
    // key排序
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);

    // 根据key排序整理正确二维数组顺序
    foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}


function is_serialized( $data ) {
    $data = trim( $data );
    if ( 'N;' == $data )
        return true;
    if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
        return false;
    switch ( $badions[1] ) {
        case 'a' :
        case 'O' :
        case 's' :
            if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
                return true;
            break;
        case 'b' :
        case 'i' :
        case 'd' :
            if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
                return true;
            break;
    }
    return false;
}


/**
 * 获取指定月份的第一天开始和最后一天结束的时间戳
 *
 * @param int $y 年份 $m 月份
 * @return array(本月开始时间，本月结束时间)
 */
function mFristAndLast($y = "", $m = ""){
    if ($y == "") $y = date("Y");
    if ($m == "") $m = date("m");
    $m = sprintf("%02d", intval($m));

    //填充字符串长度
    $y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);


    $m > 12 || $m < 1 ? $m = 1 : $m = $m;
    $firstday = strtotime($y . $m . "01000000");
    $firstdaystr = date("Y-m-01", $firstday);
    $lastday = strtotime(date('Y-m-d 23:59:59',   strtotime("$firstdaystr +1 month -1 day")));

    return array(
        "firstday" => $firstday,
        "lastday" => $lastday
    );
}

function getDay7TimeStamps($i)
{
    $t = strtotime("$i days ago");
//开始时间戳
    $data['firstday'] = mktime(0, 0, 0, date("m", $t), date("d", $t), date("Y", $t));
//结束时间戳
    $data['lastday'] = mktime(23, 59, 59, date("m", $t), date("d", $t), date("Y", $t));
    return $data;
}


/**
 * @param $expTitle
 * @param $expCellName
 * @param $expTableData
 * excel文件导出
 */
function exportExcel($expTitle, $expCellName, $expTableData)
{

    $xlsTitle    = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    $fileName    = $expTitle . date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum     = count($expCellName);
    $dataNum     = count($expTableData);
    $objPHPExcel = new \PHPExcel();//方法一

    $cellName = array(
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
        'AA',
        'AB',
        'AC',
        'AD',
        'AE',
        'AF',
        'AG',
        'AH',
        'AI',
        'AJ',
        'AK',
        'AL',
        'AM',
        'AN',
        'AO',
        'AP',
        'AQ',
        'AR',
        'AS',
        'AT',
        'AU',
        'AV',
        'AW',
        'AX',
        'AY',
        'AZ'
    );
    $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  导出时间:' . date('Y-m-d H:i:s'));
    for ($i = 0; $i < $cellNum; $i++) {
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
    }
    // Miscellaneous glyphs, UTF-8
    for ($i = 0; $i < $dataNum; $i++) {
        for ($j = 0; $j < $cellNum; $j++) {
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3),
                $expTableData[$i][$expCellName[$j][0]]);
        }
    }
    ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,
        'Excel5');//"Excel2007"生成2007版本的xlsx，"Excel5"生成2003版本的xls
    $objWriter->save('php://output');
    exit;
}

/**
 * @param $ip
 * @return string
 * 获取ip对应的地址
 */
function getIpAddress($ip)
{
    $ip_arr = \Zhuzhichao\IpLocationZh\Ip::find($ip);
    return $ip_arr[1] . $ip_arr[2];
}

/**
 * @param $url
 * @return mixed
 * 根据url获取文件大小和时间
 */
function getVideoSizeAndTime($url)
{
    $filename  = mt_rand(1000, 9999);
    $path_save = ROOT_PATH . 'public' . DS . "uploads/" . $filename . '.mp4';
    $fp_output = fopen($path_save, 'w');
    $ch        = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp_output);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp_output);

    $getID3      = new \getID3();
    $file        = $getID3->analyze($path_save);

    $str         = $file['playtime_string'];
    $exlode_time = explode(':', $str);

    if (count($exlode_time) > 2) {
        $data['video_time'] = $exlode_time[0] * 3600 + $exlode_time[1] * 60 + $exlode_time[2];
    } else {
        $data['video_time'] = $exlode_time[0] * 60 + $exlode_time[1];
    }
    $data['filesize'] = $file['filesize'];

    unlink($path_save);
    return $data;


}

function signature($post_array, $key_secret)
{
    $string_to_sign = "POST\n";
    $string_to_sign .= "mosapi.meituan.com\n";
    $string_to_sign .= "/mcs/v1\n";

    $string_to_sign .= array2xform($post_array);
    $signature = base64_encode(hash_hmac('sha256', $string_to_sign, $key_secret, true));
    return $signature;
}

function array2xform($post_array)
{
    $string = '';
    foreach ($post_array as $k => $v) {
        $string .= "&$k=" . rawurlencode($v);
    }
    $string = substr($string, 1);
    return $string;
}

function getOssFile($object)
{
    // 获取配置项
    $config = config("ALIOSS_CONFIG");
    $bucket = config('ALIOSS_CONFIG.BUCKET');

    $oss = new \OSS\OssClient($config['KEY_ID'], $config['KEY_SECRET'], $config['END_POINT']);
    try {
        $objectMeta = $oss->getObjectMeta($bucket, $object);
        return $objectMeta['content-length'];
    } catch (OssException $e) {
        return json($e->getMessage());
    }
}

/**
 * @param $type
 * @return mixed|string
 * 1作者2封面
 */
function getMaterialType($type) {
    $list = [
        1 => '作者',
        2 => '封面'
    ];
    return isset($list[$type]) ? $list[$type] : '作者';
}


/**
 * @return array
 * 此函数提供了国内的IP地址
 */
function randIP(){
    $ip_long = array(
        array('607649792', '608174079'), //36.56.0.0-36.63.255.255
        array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
        array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
        array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
        array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
        array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
        array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
        array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
        array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
        array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
    );
    $rand_key = mt_rand(0, 9);
    $ip= long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
    $headers['CLIENT-IP'] = $ip;
    $headers['X-FORWARDED-FOR'] = $ip;

    $headerArr = array();
    foreach( $headers as $n => $v ) {
        $headerArr[] = $n .':' . $v;
    }
    return $headerArr;
}

function assoc_unique($arr, $key) {

    $tmp_arr = array();

    foreach ($arr as $k => $v) {

        if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true

            unset($arr[$k]);

        } else {

            $tmp_arr[] = $v[$key];

        }

    }

    sort($arr); //sort函数对数组进行排序

    return $arr;

}

function more_array_unique($arr = array())
{
    foreach ($arr[0] as $k => $v) {
        $arr_inner_key[] = $k;   //先把二维数组中的内层数组的键值记录在在一维数组中
    }
    foreach ($arr as $k => $v) {
        $v        = implode(",", $v);    //降维 用implode()也行
        $temp[$k] = $v;      //保留原来的键值 $temp[]即为不保留原来键值
    }
//    printf("After split the array:<br>");
//    print_r($temp);    //输出拆分后的数组
//    echo"<br/>";
    $temp = array_unique($temp);    //去重：去掉重复的字符串
    foreach ($temp as $k => $v) {
        $a             = explode(",", $v);   //拆分后的重组 如：Array( [0] => james [1] => 30 )
        $arr_after[$k] = array_combine($arr_inner_key, $a);  //将原来的键与值重新合并
    }
    //ksort($arr_after);//排序如需要：ksort对数组进行排序(保留原键值key) ,sort为不保留key值
    return $arr_after;
}

function daysbetweendates($date1, $date2){
    $date1 = strtotime($date1);
    $date2 = strtotime($date2);
    $days = ceil(abs($date1 - $date2)/86400);
    return (int)$days;
}

function getNewsType($tag){
    $list = [
        1 => "企业快讯",
        2 => "精彩专题",
    ];
    return isset($list[$tag]) ? $list[$tag] : "无";
}

function getJobType($tag){
    $list = [
        1 => "全职",
        2 => "兼职",
    ];
    return isset($list[$tag]) ? $list[$tag] : "无";
}

function get_rand_str($randLength = 6, $addtime = 1, $includenumber = 0)
{
    if ($includenumber) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyz';
    }
    $len     = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    if ($addtime) {
        $tokenvalue = $randStr . time();
    }
    return $tokenvalue;
}

/**
 * @return string
 */
function get_order_sn()
{
    $order_sn = null;
    // 保证不会有重复订单号存在
    while (true) {
        $order_sn       = date('YmdHis') . rand(1000, 9999); // 订单编号
        $order_sn_count = \app\common\model\Recharge::where(['order_sn'=>$order_sn])->count('id');
        if ($order_sn_count == 0) {
            break;
        }
    }

    return $order_sn;
}


/**
 * @return string
 */
function get_order_sn_other()
{
    $order_sn = null;
    // 保证不会有重复订单号存在
    while (true) {
        $order_sn       = date('YmdHis') . rand(1000, 9999); // 订单编号
        $order_sn_count = \app\common\model\Order::where(['order_sn'=>$order_sn])->count('id');
        if ($order_sn_count == 0) {
            break;
        }
    }

    return $order_sn;
}







